package com.xqls.server.netty.future;


import com.xqls.server.dto.SoketCommonDto;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @author lubycoder@163.com
 */
public class SyncWriteFuture implements WriteFuture<SoketCommonDto> {

    private CountDownLatch latch = new CountDownLatch(1);

    // 用于清理的timeout
    private final long begin = System.currentTimeMillis();
    private long timeout;

    private SoketCommonDto requestData;
    private final String address;
    private boolean writeResult;
    private Throwable cause;
    private boolean isTimeout = false;


    private Integer value;
    public SyncWriteFuture(String address) {
        this.address = address;
    }

    public SyncWriteFuture(String address, Integer value) {
        this.address = address;
        this.value=value;
    }


    public Throwable cause() {
        return cause;
    }

    public void setCause(Throwable cause) {
        this.cause = cause;
    }

    public boolean isWriteSuccess() {
        return writeResult;
    }

    public void setWriteResult(boolean result) {
        this.writeResult = result;
    }

    public String requestId() {
        return address;
    }

    public SoketCommonDto response() {
        return requestData;
    }

    public void setResponse( SoketCommonDto requestData) {
        this.requestData = requestData;
        latch.countDown();
    }

    public boolean cancel(boolean mayInterruptIfRunning) {
        return true;
    }

    public boolean isCancelled() {
        return false;
    }

    public boolean isDone() {
        return false;
    }

    public SoketCommonDto get() throws InterruptedException, ExecutionException {
        latch.wait();
        return requestData;
    }

    public SoketCommonDto get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
        if (latch.await(timeout, unit)) {
            return requestData;
        }
        return null;
    }

    public boolean isTimeout() {
        if (isTimeout) {
            return isTimeout;
        }
        return System.currentTimeMillis() - begin > timeout;
    }

    public Integer getValue() {
        return value;
    }


}
